<template>
    <div>
        <el-card v-loading="loading">
            <!-- 按钮组 -->
            <div class="topCardBtn top-btn-container">
                <div>
                    <el-button size="mini" type="primary" style="margin-right: 1rem">启动</el-button>
                    <el-button
                        size="mini"
                        type="primary"
                        style="margin-right: 1rem"
                        @click="handleSave"
                    >保存草稿</el-button>
                </div>
                <el-button size="mini" @click="goBack">返回</el-button>
            </div>

            <div>
                <h4 class="topCardBtn">基本信息</h4>
                <el-row :gutter="20" style="align-items: center">
                    <el-col :span="3">创建人：{{ createUser }}</el-col>
                    <el-col :span="5">创建时间：{{ createTime }}</el-col>
                    <el-col :span="9">
                        选择项目
                        <el-select
                            style="width: 80%"
                            placeholder="请选择项目"
                            v-model="projectName"
                            @change="handleSelectProject"
                        >
                            <el-option
                                v-for="(project, idx) in projectList"
                                :key="idx"
                                :label="project.projectName"
                                :value="project"
                            ></el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="7">
                        选择施工段
                        <el-select
                            style="width: 80%"
                            placeholder="请选择选择施工段"
                            v-model="construction"
                            @change="handleSelectConstruction"
                        >
                            <el-option
                                v-for="(construction, idx) in constructionList"
                                :key="idx"
                                :label="construction.constructionIndex + '-' + construction.constructionName"
                                :value="construction"
                            ></el-option>
                        </el-select>
                    </el-col>
                </el-row>
            </div>
        </el-card>
        <!-- 进度表 -->
        <el-card>
            <h4 class="topCardBtn">进度表</h4>
            <el-row :gutter="20" style="height: 50rem">
                <el-col :span="12">
                    <el-table :data="scheduleData" border>
                        <el-table-column label="序号" prop="index" width="50" align="center"></el-table-column>
                        <el-table-column label="节点名称" prop="nodeName" width="110" align="center"></el-table-column>
                        <el-table-column label="开始时间" align="center">
                            <template #default="scope">
                                <el-date-picker
                                    :editable="false"
                                    :disabled="scope.row.nodeName === '总任务'"
                                    style="width: 10rem"
                                    v-model="scope.row.startTime"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                    format="YYYY-MM-DD"
                                    placeholder="请选择开始时间"
                                    @change="(val) => handleStartTime(scope.$index, scope.row, val)"
                                ></el-date-picker>
                            </template>
                        </el-table-column>
                        <el-table-column label="结束时间" align="center">
                            <template #default="scope">
                                <el-date-picker
                                    :editable="false"
                                    :disabled="scope.row.nodeName === '总任务'"
                                    style="width: 10rem"
                                    value-format="YYYY-MM-DD"
                                    v-model="scope.row.endTime"
                                    format="YYYY-MM-DD"
                                    type="date"
                                    placeholder="请选择结束时间"
                                    @change="(val) => handleEndTime(scope.$index, scope.row, val)"
                                ></el-date-picker>
                            </template>
                        </el-table-column>
                        <el-table-column label="工期" prop="duration" width="80" align="center"></el-table-column>
                    </el-table>
                </el-col>
                <el-col :span="12">
                    <gstc :config="config" :key="key1" />
                </el-col>
            </el-row>
        </el-card>
        <!-- 任务列表 -->
        <el-card>
            <h4 class="topCardBtn">任务列表</h4>
            <div class="topCardBtn">
                <el-button size="mini" type="primary" @click="handleSelectTemplate">选择模版</el-button>
                <!-- <el-button size="mini">删除</el-button> -->
            </div>
            <el-row :gutter="20" style="height: 50rem">
                <el-col :span="12">
                    <el-table :data="jobData" border>
                        <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
                        <el-table-column label="任务名称" prop="jobName" width="130" align="center"></el-table-column>
                        <el-table-column label="开始时间" align="center" width="200">
                            <template #default="scope">
                                <el-date-picker
                                    :editable="false"
                                    style="width: 10rem"
                                    v-model="scope.row.startTime"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                    format="YYYY-MM-DD"
                                    placeholder="请选择开始时间"
                                    @change="(val) => handleStartTimeJob(scope.$index, scope.row, val)"
                                    :disabled-date="disabledDate"
                                ></el-date-picker>
                            </template>
                        </el-table-column>
                        <el-table-column label="结束时间" align="center" width="200">
                            <template #default="scope">
                                <el-date-picker
                                    :editable="false"
                                    style="width: 10rem"
                                    value-format="YYYY-MM-DD"
                                    v-model="scope.row.endTime"
                                    format="YYYY-MM-DD"
                                    type="date"
                                    placeholder="请选择结束时间"
                                    @change="(val) => handleEndTimeJob(scope.$index, scope.row, val)"
                                ></el-date-picker>
                            </template>
                        </el-table-column>
                        <el-table-column label="工期" prop="duration" width="80" align="center"></el-table-column>
                        <el-table-column
                            label="工种"
                            prop="userOrTypeWork"
                            width="130"
                            align="center"
                        >
                            <template #default="scope">
                                <el-select
                                    @change="(val) => handleSelectRole(val, scope.$index, scope.row)"
                                    v-model="scope.row.userOrTypeWork"
                                    filterable
                                    placeholder="请选择工种"
                                >
                                    <el-option
                                        v-for="(role, idx) in roleList"
                                        :ket="idx"
                                        :label="role.name"
                                        :value="role"
                                    ></el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="人员" width="200" align="center">
                            <template #default="scope">
                                <el-select
                                    style="width: 10rem"
                                    @change="(val) => handleSelectUser(val, scope.$index, scope.row)"
                                    v-model="scope.row.user"
                                    filterable
                                    placeholder="请选择人员"
                                >
                                    <el-option
                                        v-for="(user, idx) in scope.row.userList"
                                        :ket="idx"
                                        :label="user.userName"
                                        :value="user"
                                    ></el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="人数" width="130" align="center">
                            <template #default="scope">
                                <el-input placeholder="请输入人数" v-model="scope.row.peopleNumber" />
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button type="text" @click="handleDeteleJob(scope.$index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
                <el-col :span="12">
                    <gstc1 :config="configjob" :key="key2" />
                </el-col>
            </el-row>
        </el-card>
        <el-dialog title="选择模版" v-model="dialogFormVisible">
            <div style="display:flex">
                <el-form :model="form" :rules="rules" ref="ruleForm" style="width: 100%">
                    <el-row>
                        <el-col :span="8" style="text-align: left">
                            <el-form-item label="分部名称" prop="selectDistr">
                                <el-select
                                    placeholder="请选择分部名称"
                                    @change="handleSelectDistr"
                                    v-model="form.selectDistr"
                                >
                                    <el-option
                                        v-for="(item ,idx) in distributionList"
                                        :key="idx"
                                        :label="item.name_"
                                        :value="item"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" style="text-align: left; margin-left: 2rem">
                            <el-form-item label="分项名称" prop="selectShare">
                                <el-select
                                    placeholder="请选择分项名称"
                                    @change="handleSelectShare"
                                    v-model="form.selectShare"
                                >
                                    <el-option
                                        v-for="(item ,idx) in shareList"
                                        :key="idx"
                                        :label="item.fxgcmc"
                                        :value="item"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="3">
                            <el-button
                                type="primary"
                                size="mini"
                                @click="getTemplateDataIdByShare('ruleForm')"
                            >查询</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <el-tree
                ref="tree"
                :data="templateData"
                show-checkbox
                default-expand-all
                node-key="id"
                highlight-current
                :props="defaultProps"
            />
            <div class="buttons">
                <el-button type="primary" @click="getCheckedNodes">确定</el-button>
                <el-button @click="dialogFormVisible = false">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import GSTCComponent, { GSTC } from '../../components/GSTC.vue';
import GSTCComponent1, { GSTC as GSTC1 } from '../../components/GSTC1.vue';
import gstcConfig from '../../utils/gstcConfig'

const GSTCID = GSTC.api.GSTCID;
const GSTCID1 = GSTC1.api.GSTCID;
let subs = [];
export default {
    components: {
        gstc: GSTCComponent,
        gstc1: GSTCComponent1,
    },
    data() {
        return {
            config: '', // 甘特图配置
            configjob: '', // 甘特图配置
            loading: false,
            createUser: '',
            createTime: '',
            projectName: '',
            projectId: '',
            projectNo: '',
            projectList: [],
            scheduleData: [{
                index: '1',
                nodeName: '总任务',
            }, {
                index: '2',
                nodeName: '现场勘查',
            }, {
                index: '3',
                nodeName: '放样验收',
            }, {
                index: '4',
                nodeName: '隔墙隐蔽验收',
            }, {
                index: '4a',
                nodeName: '墙面清洁',
            }, {
                index: '4b',
                nodeName: '地面清洁',
            }, {
                index: '5',
                nodeName: '天花隐蔽验收',
            }, {
                index: '6',
                nodeName: 'PPCG初体验',
            }, {
                index: '7',
                nodeName: '业主初验',
            }, {
                index: '8',
                nodeName: '业主复验',
            }, {
                index: '9',
                nodeName: '业主搬家',
            }],
            jobData: [],
            userList: [],
            dialogFormVisible: false,
            templateData: [],
            defaultProps: {
                children: 'children',
                label: 'jobName',
            },

            distributionList: [],
            shareList: [],
            form: {
                selectDistr: '',
                selectDistrId: '',
                selectShare: '',
                selectShareId: '',
            },
            rules: {
                selectDistr: [
                    {
                        required: true,
                        message: '请选择分部名称',
                        trigger: 'change',
                    },
                ],
                selectShare: [
                    {
                        required: true,
                        message: '请选择分项名称',
                        trigger: 'change',
                    },
                ],
            },
            formLabelWidth: '120px',
            jobStartTime: '',
            jobEndTime: '',
            constructionList: [],
            projectUserList: [],
            construction: '',
            constructionId: '',
            constructionIndex: '',
            constructionName: '',
            masterList: [],
            key1: '',
            key2: '',
            isSave: true,
        }
    },
    created() {
        this.setGSTC()
        this.setGSTCJob()
        this.createUser = localStorage.getItem('userName')
        this.createTime = this.$moment().format('YYYY-MM-DD HH:mm:ss')
        // 加载太慢，暂时注释
        this.getProjectList()
    },
    methods: {
        // 查询项目列表
        getProjectList() {
            this.loading = true
            const param = { curPage: 1, pageSize: 1000000, params: {} }
            this.$axios.post(`/form/formCustSql/view/list_ppcgLoiProjectVo`, param).then(res => {
                if (res.isOk) {
                    this.loading = false
                    this.projectList = res.data.list
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 选择项目
        handleSelectProject(item) {
            this.projectId = item.uuid
            this.projectName = item.projectName
            this.projectNo = item.projectNo
            this.constructionList = []
            this.construction = ''
            this.constructionId = ''
            this.constructionIndex = ''
            this.constructionName = ''
            this.projectUserList = []
            this.isSave = true
            this.getProjectUserDataIdByProId()
        },
        // 查询项目成员主表id
        getProjectUserDataIdByProId() {
            const param = { curPage: 1, pageSize: 10, params: { queryData: [{ name: 'projectNo', con: "like", val: this.projectNo }] } }
            this.$axios.post(`/form/formCustSql/view/list_projectVoProjectUserMst`, param).then(res => {
                if (res.isOk) {
                    if (res.data.list.length > 0)
                        this.getProjectUserDataByMasterId(res.data.list[0].id_)
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 根据项目成员主表id查询字表详情
        getProjectUserDataByMasterId(id) {
            this.$axios.post(`/form/formDefData/getData?key=projectVoProjectUser&id=${id}&sql=`,).then(res => {
                if (res.isOk) {
                    this.constructionList = res.data.data.projectVoProjectUser.projectVoProjectUserConstructionList
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        handleSelectConstruction(item) {
            this.constructionId = item.id
            this.construction = item.constructionIndex + '-' + item.constructionName
            this.constructionIndex = item.constructionIndex
            this.constructionName = item.constructionName
            this.projectUserList = item.projectVoProjectUserDtlList
            this.getSave()
        },
        getSave() {
            let param = { curPage: 1, pageSize: 10, params: { queryData: [{ name: "construction_id_", con: "=", val: this.constructionId }] } }
            this.$axios.post(`/form/formCustSql/view/list_ppcgSecondaryScheduleMst`, param).then(res => {
                if (res.isOk) {
                    if (res.data.count > 0) {
                        this.isSave = false
                        this.$ElMessage({
                            message: `施工段${this.constructionIndex}-${this.constructionName}已存在`,
                            type: 'error',
                        })
                    }
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 甘特图设置开始，不知道为什么这么写，感觉没什么用，但是又不敢删除
        onState(state1) {
            this.state1 = state1;
            subs.push(
                state1.subscribe(`config.chart.items.${GSTCID('1')}`, (item) => {
                    console.log('item 1 changed', item);
                })
            );
            subs.push(
                state1.subscribe(`config.list.rows.${GSTCID('1')}`, (row) => {
                    console.log('row 1 changed', row);
                })
            );
        },
        onLoaded(gstc) {
            console.log('gstc loaded!', gstc);
            window.gstc = gstc; // you can console it out
            setTimeout(() => {
                const item1 = this.config.chart.items[GSTCID('1')];
                item1.label = 'label changed dynamically';
                item1.time.end += 2 * 24 * 60 * 60 * 1000;
                const row1 = this.config.list.rows[GSTCID('1')];
                row1.label = 'label changed dynamically';
            }, 4000);
        },
        // 甘特图设置结束，不知道为什么这么写，感觉没什么用，但是又不敢删除

        // 选择开始时间
        handleStartTime(index, row, val) {
            if (!this.isSave) {
                row.startTime = ''
                this.$ElMessage({
                    message: `施工段${this.constructionIndex}-${this.constructionName}已存在`,
                    type: 'error',
                })
                return
            }
            if (!this.projectNo || !this.constructionId) {
                row.startTime = ''
                this.$ElMessage({
                    message: '请先选择项目和施工段',
                    type: 'warning',
                })
                return
            }
            if (!this.scheduleData[0].startTime) {
                this.scheduleData[0].startTime = val
            }
            let diffTime = this.$moment(val).diff(this.scheduleData[0].startTime, 'day')
            if (diffTime < 0) {
                this.scheduleData[0].startTime = val
            }
            if (row.endTime)
                row.duration = (this.$moment(row.endTime).diff(val, 'day')) + 1
            let duration = 0
            for (let i = 1; i < this.scheduleData.length; i++) {
                duration = duration + (this.scheduleData[i].duration ? Number(this.scheduleData[i].duration) : 0)
            }
            this.scheduleData[0].duration = duration
            if (row.endTime)
                this.setGSTC()
        },
        // 选择结束时间
        handleEndTime(index, row, val) {
            if (!this.isSave) {
                row.endTime = ''
                this.$ElMessage({
                    message: `施工段${this.constructionIndex}-${this.constructionName}已存在`,
                    type: 'error',
                })
                return
            }
            if (!this.projectNo || !this.constructionId) {
                row.endTime = ''
                this.$ElMessage({
                    message: '请先选择项目和施工段',
                    type: 'warning',
                })
                return
            }
            let rowDiff = this.$moment(val).diff(row.startTime, 'day')
            if (rowDiff < 0) {
                row.endTime = ''
                this.$ElMessage({
                    message: '结束时间不能小于开始时间',
                    type: 'error',
                })
                return
            }
            if (!this.scheduleData[0].endTime) {
                this.scheduleData[0].endTime = val
            }
            let diffTime = this.$moment(val).diff(this.scheduleData[0].endTime, 'day')
            if (diffTime > 0) {
                this.scheduleData[0].endTime = val
            }
            if (row.startTime)
                row.duration = (this.$moment(val).diff(row.startTime, 'day')) + 1
            let duration = 0
            for (let i = 1; i < this.scheduleData.length; i++) {
                duration = duration + (this.scheduleData[i].duration ? Number(this.scheduleData[i].duration) : 0)
            }
            this.scheduleData[0].duration = duration ? duration : ''
            if (row.startTime)
                this.setGSTC()
        },
        // 设置进度表甘特图
        setGSTC() {
            const columns = {
                data: {
                    nodeName: {
                        id: "nodeName",
                        data: "nodeName",
                        width: 120,
                        // expander: true, // 是否可以折叠
                        header: {
                            content: "节点名称"
                        }
                    },
                }
            }
            let rows = {}, items = {}
            this.scheduleData.map(d => {
                rows[d.nodeName] = {
                    id: d.nodeName,
                    nodeName: d.nodeName,
                }
                items[d.nodeName] = {
                    id: d.nodeName,
                    rowId: d.nodeName,
                    nodeName: d.nodeName,
                    // 设置时间，刚加载页面没有时间
                    time: {
                        start: d.startTime ? GSTC.api.date(d.startTime).valueOf() : '',
                        end: d.endTime ? GSTC.api.date(d.endTime).valueOf() + 1 * 24 * 60 * 60 * 1000 : GSTC.api.date(d.endTime).valueOf(), // 结束时间包含结束时间当天
                    },
                    // 默认红色
                    style: {  // 每个块的样式
                        background: d.nodeName === '总任务' ? 'rgb(0, 229, 181)' : 'rgb(45, 147, 250)'
                    }
                }
            })
            // 甘特图日期区间设置
            const chart = {
                from: this.scheduleData[0].startTime ? this.scheduleData[0].startTime : this.$moment(),
                to: this.scheduleData[0].endTime ? this.scheduleData[0].endTime : this.$moment().add(6, 'days')
            }
            this.config = gstcConfig.setConfig(columns, rows, items, chart)
        },

        // 设置任务列表甘特图
        setGSTCJob() {
            const columns = {
                data: {
                    jobName: {
                        id: "jobName",
                        data: "jobName",
                        width: 120,
                        // expander: true, // 是否可以折叠
                        header: {
                            content: "任务名称"
                        }
                    },
                }
            }
            let rows = {}, items = {}
            this.jobData.map(d => {
                rows[d.jobName] = {
                    id: d.jobName,
                    jobName: d.jobName,
                }
                items[d.jobName] = {
                    id: d.jobName,
                    rowId: d.jobName,
                    jobName: d.jobName,
                    parentID: d.parentId,
                    // 设置时间，刚加载页面没有时间
                    time: {
                        start: d.startTime ? GSTC.api.date(d.startTime).valueOf() : '',
                        end: d.endTime ? GSTC.api.date(d.endTime).valueOf() + 1 * 24 * 60 * 60 * 1000 : GSTC.api.date(d.endTime).valueOf(), // 结束时间包含结束时间当天
                    },
                    // 默认红色
                    style: {  // 每个块的样式
                        background: 'rgb(45, 147, 250)'
                    }
                }
            })
            // 甘特图日期区间设置
            const chart = {
                from: this.jobStartTime ? this.jobStartTime : this.$moment(),
                to: this.jobEndTime ? this.jobEndTime : this.$moment().add(6, 'days')
            }
            this.configjob = gstcConfig.setConfig(columns, rows, items, chart)
        },
        handleSelectTemplate() {
            if (!this.isSave) {
                this.$ElMessage({
                    message: `施工段${this.constructionIndex}-${this.constructionName}已存在`,
                    type: 'error',
                })
                return
            }
            if (!this.projectNo || !this.constructionId) {
                this.$ElMessage({
                    message: '请先选择项目和施工段',
                    type: 'warning',
                })
                return
            }
            this.dialogFormVisible = true
            this.form.selectDistr = ''
            this.form.selectDistrId = ''
            this.form.selectShare = ''
            this.form.selectShareId = ''
            this.templateData = []
            this.getDistributionData()
        },

        // 查询分部名称
        getDistributionData() {
            this.$axios.post(`/form/formDefData/getList_ppcgDistribution?order=asc&offset=0&limit=10000`).then(res => {
                if (res.isOk) {
                    this.distributionList = res.rows
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 选择分部名称
        handleSelectDistr(val) {
            this.form.selectDistr = val.name_
            this.form.selectDistrId = val.id_
            this.form.selectShare = ''
            this.form.selectShareId = ''
            this.getShareData()
        },

        // 查询分项名称
        getShareData() {
            const param = { curPage: this.page, pageSize: this.pagesize, params: { queryData: [{ name: "master_id_", con: "like", val: this.form.selectDistrId }] } }
            this.$axios.post(`/form/formCustSql/view/list_ppcgShare`, param).then(res => {
                if (res.isOk) {
                    this.shareList = res.data.list
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 选择分项名称
        handleSelectShare(val) {
            this.form.selectShare = val.fxgcmc
            this.form.selectShareId = val.id_
        },
        // 根据分项名称&id查询进度模版id
        getTemplateDataIdByShare(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    const param = { curPage: 1, pageSize: 10, params: { queryData: [{ name: "share_id_", con: "like", val: this.form.selectShareId }, { name: "share_name_", con: "like", val: this.form.selectShare }] } }
                    this.$axios.post(`/form/formCustSql/view/list_ppcgScheduleTemplateMaintenanceMst`, param).then(res => {
                        if (res.isOk) {
                            const newData = res.data.list
                            if (newData.length === 0) {
                                this.templateData = []
                            } else
                                this.getTemplateData(newData[0].id_)
                        } else {
                            this.$ElMessage({
                                message: res.msg,
                                type: 'error',
                            })
                        }
                    })
                }
            })
        },
        // 根据进度模版id查询详情
        getTemplateData(id) {
            this.$axios.post(`/form/formDefData/getData?key=ppcgScheduleTemplateMaintenanceMst&id=${id}&sql=1`).then(res => {
                if (res.isOk) {
                    const newData = res.data.data.ppcgScheduleTemplateMaintenanceMst.ppcgScheduleTemplateMaintenanceDtlList
                    // 多级树处理
                    const parentList = newData.filter(d => { return d.parentId === '0' })
                    const childList = newData.filter(d => { return d.parentId != '0' })
                    parentList.map(item => {
                        // 判断children是不是数字
                        if (typeof (item.children) === 'number') {
                            item.children = []
                        }
                        childList.map(child => {
                            if (item.wbs === child.parentId) {
                                delete child.children
                                item.children.push(child)
                            }
                            item.children?.map(d => {
                                if (d.wbs === child.parentId) {
                                    if (!d.children) {
                                        d.children = []
                                    }
                                    d.children.push(child)
                                }
                            })
                        })
                    })
                    this.templateData = parentList
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        // 获取已选择模版节点
        getCheckedNodes() {
            const checkNodes = this.$refs.tree.getCheckedNodes()
            let jobData = []
            checkNodes.map(node => {
                let isExist = false
                if (this.jobData.length === 0) {
                    isExist = false
                }
                for (let d of this.jobData) {
                    if (d.jobName != node.jobName) {
                        isExist = false
                    } else {
                        isExist = true
                        break
                    }
                }
                if (!isExist) {
                    node.userList = []
                    this.projectUserList.filter(user => {
                        if (node.userOrTypeWork === user.roleName) {
                            node.userList.push(user)
                            node.user = node.userList.length > 0 ? node.userList[0].userName : ''
                        }
                    })
                    delete node.id
                    jobData.push(node)
                }
            })
            this.jobData.push(...jobData)
            this.masterList.push({
                distrId: this.form.selectDistrId,
                distrName: this.form.selectDistr,
                shareId: this.form.selectShareId,
                shareName: this.form.selectShare,
                ppcgSecondaryScheduleJobDtlList: jobData,
            })
            this.dialogFormVisible = false
            this.setGSTCJob()
            this.getRoleData()
        },
        // 查询角色
        getRoleData() {
            this.$axios.get(`/org/role/listJson?order=asc&offset=0&limit=10000&name_%5EVLK=&alias_%5EVLK=&enabled_%5EVLK=`).then(res => {
                if (res.isOk) {
                    const newData = res.rows
                    // 过滤启用状态&name不为空
                    this.roleList = newData.filter(d => { return d.enabled && d.name })
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        handleSelectRole(val, index, item) {
            this.jobData[index].userOrTypeWork = val.name
            this.jobData[index].userOrTypeWorkId = val.id
            this.projectUserList.map(user => {
                if (val.name === user.roleName) {
                    if (!val.userList)
                        val.userList = []
                    val.userList.push(JSON.parse(JSON.stringify(user)))
                    val.user = val.userList.length > 0 ? val.userList[0].userName : ''
                }
            })
            this.jobData[index].userList = val.userList
            this.jobData[index].user = val.user
        },
        getCheckedKeys() {
            console.log(this.$refs.tree.getCheckedKeys())
        },
        // 选择任务开始时间
        handleStartTimeJob(index, row, val) {
            let diff = this.$moment(val).diff(this.scheduleData[0].startTime, 'days')
            if (diff < 0) {
                this.$ElMessage({
                    message: '开始时间不能小于总任务开始时间',
                    type: 'warning'
                })
                row.startTime = ''
                return
            }
            if (!this.jobStartTime) {
                this.jobStartTime = val
            }
            let diffTime = this.$moment(val).diff(this.jobStartTime, 'day')
            if (diffTime < 0) {
                this.jobStartTime = val
            }
            if (row.endTime) {
                row.duration = (this.$moment(row.endTime).diff(val, 'day')) + 1
                this.setGSTCJob()
            }
        },
        // 选择任务结束时间
        handleEndTimeJob(index, row, val) {
            let diff = this.$moment(this.scheduleData[0].endTime).diff(val, 'days')
            if (diff < 0) {
                this.$ElMessage({
                    message: '开始时间不能大于总任务开始时间',
                    type: 'warning'
                })
                row.endTime = ''
                return
            }
            let rowDiff = this.$moment(val).diff(row.startTime, 'day')
            if (rowDiff < 0) {
                row.endTime = ''
                this.$ElMessage({
                    message: '结束时间不能小于开始时间',
                    type: 'error',
                })
                return
            }
            if (!this.jobEndTime) {
                this.jobEndTime = val
            }
            let diffTime = this.$moment(val).diff(this.jobEndTime, 'day')
            if (diffTime > 0) {
                this.jobEndTime = val
            }

            if (row.startTime) {
                row.duration = (this.$moment(val).diff(row.startTime, 'day')) + 1
                this.setGSTCJob()
            }
        },
        handleDeteleJob(index) {
            this.$ElMessageBox.confirm(
                '确定删除该条数据吗？',
                '警告',
                {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                this.jobData.splice(index, 1)

                this.key2 = new Date().toString()
                this.setGSTCJob()
            })
        },
        // 保存草稿
        handleSave() {
            if (!this.isSave) {
                this.$ElMessage({
                    message: `施工段${this.constructionIndex}-${this.constructionName}已存在`,
                    type: 'error',
                })
                return
            }
            this.scheduleData.map(d => {
                d.masterId = ''
            })
            this.jobData.map(d => {
                d.masterId = ''
                delete d.userList
                delete d.children
            })
            const param = {
                ppcgSecondaryScheduleMst: {
                    createTime: this.createTime,
                    createUser: this.createUser,
                    ppcgSecondaryScheduleDtlList: this.scheduleData,
                    ppcgSecondaryScheduleJobMstList: this.masterList,
                    projectId: this.projectId,
                    projectNo: this.projectNo,
                    projectName: this.projectName,
                    constructionId: this.constructionId,
                    constructionIndex: this.constructionIndex,
                    constructionName: this.constructionName,
                }
            }
            this.$axios.post(`/form/formDefData/saveData?key=ppcgSecondaryScheduleMst&sql=`, param).then(res => {
                if (res.isOk) {
                    this.$ElMessage({
                        message: '保存成功',
                        type: 'success'
                    })
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        },
        goBack() {
            this.$router.go(-1)
        },
    },
    watch: {
        startTime(val, oldval) {
            console.log('this.startTime====>', this.startTime)
            this.disabledDate = (time) => {
                return time.getTime() > this.startTime
            }
        }

    },
    beforeUnmount() {
        subs.forEach((unsub) => unsub());
    },
}
</script>

<style scoped>
</style>